﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaCustomer;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaCustomer;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.Common.Model.NPOI;
using YNTK.Common.Configuration;
using YNTK.DataEncryption;
using YNTK.ClayObject;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaCustomer
{
    /// <summary>
    /// 客户信息服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaCustomer", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaCustomerService : IZyOaCustomerService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaCustomerEntity> _zyOaCustomerRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaCustomerService"/>类型的新实例
        /// </summary>
        public ZyOaCustomerService(
            ISqlSugarRepository<ZyOaCustomerEntity> zyOaCustomerRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyOaCustomerRepository = zyOaCustomerRepository;            
            _db = _zyOaCustomerRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaCustomerEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaCustomerInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取客户信息列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> ZyOaCustomer([FromQuery] ZyOaCustomerListQueryInput input)
        {
            var sidx = input.sidx == null ? "createTime" : input.sidx;
            var areaList = input.area != null ? input.area.Split(',').ToList().ToJson() :null;
            var data = await _db.Queryable<ZyOaCustomerEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.name), p => p.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.customerTypeId), p => p.CustomerTypeId.Equals(input.customerTypeId))
                .WhereIF(!string.IsNullOrEmpty(input.industry), p => p.Industry.Equals(input.industry))
                .Select(it=> new 
                {
                    id = it.Id,
                    userName=it.UserName,
                    name=it.Name,
                    mobile=it.Mobile,
                    address=it.Address,
                    area=it.Area,
                    customerTypeId=it.CustomerTypeId,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    desPerson=it.DesPerson,
                    industry=it.Industry,
                    profile=it.Profile,
                    customerId=it.CustomerId,
                }).MergeTable().Select<ZyOaCustomerListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaCustomerListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建客户信息
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaCustomerCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaCustomerEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.Creater = _userManager.UserId;
            entity.CreateTime = DateTime.Now;  
            entity.CustomerId = await _billRuleService.GetBillNumber("ZYKH");
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
		/// 获取客户信息无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] ZyOaCustomerListQueryInput input)
        {
            var sidx = input.sidx == null ? "createTime" : input.sidx;
            var areaList = input.area != null ? input.area.Split(',').ToList().ToJson() : null;
            var data = await _db.Queryable<ZyOaCustomerEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.name), p => p.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.customerTypeId), p => p.CustomerTypeId.Equals(input.customerTypeId))
                .WhereIF(!string.IsNullOrEmpty(input.industry), p => p.Industry.Equals(input.industry))
                .Select(it=> new 
                {
                    id = it.Id,
                    userName=it.UserName,
                    name=it.Name,
                    mobile=it.Mobile,
                    address=it.Address,
                    area=it.Area,
                    customerTypeId=it.CustomerTypeId,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    desPerson=it.DesPerson,
                    industry=it.Industry,
                    profile=it.Profile,
                    customerId=it.CustomerId,
                }).MergeTable().Select<ZyOaCustomerListOutput>().OrderBy(sidx+" "+input.sort).ToListAsync();
                return data;
        }

        /// <summary>
		/// 导出客户信息
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ZyOaCustomerListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<ZyOaCustomerListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.ZyOaCustomer(input));
                exportData = data.Solidify<TkPageResult<ZyOaCustomerListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"客户编码\",\"field\":\"customerId\"},{\"value\":\"客户名称\",\"field\":\"name\"},{\"value\":\"客户行业\",\"field\":\"industry\"},{\"value\":\"客户类型\",\"field\":\"customerTypeId\"},{\"value\":\"联系人\",\"field\":\"userName\"},{\"value\":\"联系电话\",\"field\":\"mobile\"},{\"value\":\"所属区域\",\"field\":\"area\"},{\"value\":\"客户地址\",\"field\":\"address\"},{\"value\":\"客户经理\",\"field\":\"desPerson\"},{\"value\":\"客户描述\",\"field\":\"profile\"},{\"value\":\"创建人\",\"field\":\"creater\"},{\"value\":\"创建时间\",\"field\":\"createTime\"},]".ToList<ParamsModel>();           
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "客户信息.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<ZyOaCustomerListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "YNTK")
            };
            return output;
        }

        /// <summary>
        /// 批量删除客户信息
        /// </summary>
        /// <param name="ids">主键数组</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _db.Queryable<ZyOaCustomerEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    //开启事务
                    _db.Ado.BeginTran();
                    //批量删除客户信息
                    await _db.Deleteable<ZyOaCustomerEntity>().In(d => d.Id,ids).ExecuteCommandAsync();
                    //关闭事务
                    _db.Ado.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.Ado.RollbackTran();
                    throw YNTKException.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新客户信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaCustomerUpInput input)
        {
            var entity = input.Adapt<ZyOaCustomerEntity>();
            entity.Modifyer = _userManager.UserId;
            entity.ModifyTime = DateTime.Now;  
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除客户信息
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaCustomerEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaCustomerEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }




    }
}
